package com.huayun.dcsp.common.jedis;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisSource {
	private static JedisPool jedisPool = null;
	
    private int maxIdle=10;  
    public void setMaxIdle(int maxIdle) {  
        this.maxIdle = maxIdle;  
    }  
    
    private int maxTotal=50;  
    public void setMaxTotal(int maxTotal) {  
        this.maxTotal = maxTotal;  
    } 
    
    private long maxWaitMillis=5000;
    public void setMaxWaitMillis(long maxWaitMillis) {  
        this.maxWaitMillis = maxWaitMillis;  
    } 
    
    private String host="localhost";  
    public void setHost(String host) {  
        this.host = host;  
    } 
    
    private int port=6379;  
    public void setPort(int port) {  
        this.port = port;  
    }
    
    private int timeOut=2000;  
    public void setTimeOut(int timeOut) {  
        this.timeOut = timeOut;  
    } 
    
    private String password="";  
    public void setPassword(String password) {  
        this.password = password;  
    } 
    
    public void initialPool() {
	
		try {
			final JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(maxTotal);
			config.setMaxIdle(maxIdle);
			config.setMaxWaitMillis(maxWaitMillis);
			config.setTestOnBorrow(false);

			jedisPool = new JedisPool(config, host, port, timeOut,null);
			
			System.out.println("******************************");
	    	System.out.println("jedisPool is created:"+host+" "+port+" "+password);  
	        System.out.println("******************************");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}

	}
    
    public synchronized Jedis getJedisInstance() {
		try {
			if (jedisPool != null) {
				Jedis resource = jedisPool.getResource();
				return resource;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
    
    public synchronized Jedis getJedisInstance(final int dbIndex) {
		try {
			if (jedisPool != null) {
				Jedis resource = jedisPool.getResource();
				resource.select(dbIndex);
				return resource;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public void returnResource(final Jedis jedis) {
		if (jedis != null) {
			jedisPool.returnResource(jedis);
		}
	}
    
}
